require 'rss'
require 'open-uri'

class ExternalRssFeed < ActiveRecord::Base
  validates_presence_of :name, :url
  validates_uniqueness_of :name, :url
  
  def title
    unless @feed
      parse_feed
    end
    
    @feed.channel.title
  end
  
  def link
    unless @feed
      parse_feed
    end
    
    @feed.channel.link
  end
  
  def description
    unless @feed
      parse_feed
    end
    
    @feed.channel.description
  end
  
  def story_count
    unless @feed
      parse_feed
    end
    
    @feed.items.size
  end
  
  def items
    unless @feed
      parse_feed
    end
    
    @feed.items
  end
  
  def valid?
    if fetch_feed
      if parse_feed
        true
      else
        false
      end
    else
      false
    end
  end
  
  def cache?
    if self.cache_datetime.nil?
      false
    elsif 4.hours.ago > self.cache_datetime
      false
    else
      true
    end
  end
  
  def fetch_feed
    if self.cache?
      @raw_content = self.cache
    else
      open(self.url) do |s|
        @raw_content = s.read
        
        self.cache = @raw_content
        self.cache_datetime = Time.now
      end
    end
  end
    
  def parse_feed
    unless @raw_content
      fetch_feed
    end
    
    @feed = RSS::Parser.parse(@raw_content, false)
  end
end